package com.example.newheze.Monitor;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.example.newheze.FieldMessage.CurrentData;
import com.example.newheze.R;

public class MonitorService extends Service {
    CurrentData currentData;
    public MonitorService() {

    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        currentData=new CurrentData();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        executeNetListen();
        return super.onStartCommand(intent, flags, startId);

    }
    private void executeNetListen() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                JudgeData();
                executeNetListen();
            }
        }, 300000);  //每5min执行一次HTTP请求并判断结果
    }
    private void JudgeData(){
        if(currentData.getAirTemperature()<0){
            StartNoti("空气温度异常");
        }
        if(currentData.getAirHumidity()<0){
            StartNoti("空气湿度异常");
        }
        if(currentData.getSoilHumidity1()<0){
            StartNoti("土壤湿度1异常");
        }
        if(currentData.getSoilHumidity2()<0){
            StartNoti("土壤湿度2异常");
        }
    }
    private void StartNoti(String string){
        NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Notification notification=new NotificationCompat.Builder(this)
                .setContentTitle("警告！")
                .setContentText(string)
                .setWhen( System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .build();
        notificationManager.notify(1,notification);
    }

}
